package com.kinon.ceshiaccount.fragment.home;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.adapter.DiningTypeAdapter;
import com.kinon.ceshiaccount.adapter.LunchAdapter;
import com.kinon.ceshiaccount.adapter.urgent.U_LunchAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.RoleBean;
import com.kinon.ceshiaccount.bean.base.LunchBean;
import com.kinon.ceshiaccount.bean.urgent.Card;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;
import com.kinon.ceshiaccount.util.LunchTypeUtil;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SoundPoolManage;
import com.kinon.ceshiaccount.util.SysTimeManage;
import com.kinon.ceshiaccount.util.ToastUtil;
import com.kinon.ceshiaccount.view.CustomDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Response;
import sunmi.ds.callback.ISendCallback;

import static org.litepal.crud.DataSupport.where;

/**
 * Created by luohao on 2017-06-16.
 * 午餐界面
 */

public class LunchFragment extends BaseFragment implements View.OnClickListener {
    public static int amount = 0;
    //紧急情况下使用的数据
    ArrayList<U_SettletmentBean> selist;
    U_LunchAdapter uWAdapter = null;
    Gson gson = new Gson();
    ToastUtil toastUtil = new ToastUtil();
    Handler myHandler = new Handler();
    Runnable delayRun = new Runnable() {
        @Override
        public void run() {
            SunmiSdkManage.getInstance().showWelcomeImg();
        }
    };
    private View mView;
    /**
     * 餐卡id
     */
    private EditText et_lunchId;
    /**
     * 午餐人数
     */
    private TextView tv_lunchNum;
    /**
     * 午餐就餐信息
     */
    private ListView list_lunch;
    /**
     * 显示就餐类型的布局
     */
    private RelativeLayout rl_select;
    /**
     * 选择就餐类型
     */
    private GridView grid_diningType;
    /**
     * 显示就餐类型
     */
    private TextView tv_lunchType;
    /**
     * 清空卡号残余
     */
    private Button btn_clearCard;
    private LunchAdapter adapter = null;
    private ArrayList<LunchBean> lunchList = null;
    private Context context;
    /**
     * 唯一标识
     */
    private long nonce_str;
    private String on_card = "";
    /**
     * 就餐类型
     */
    private int mType = 0;
    private ArrayList<RoleBean> binings = null;
    private DiningTypeAdapter diningAdapter = null;
    private int mIndex = 0;
    /**
     * 第一次进入的时间
     */
    private long firstTime;
    private boolean isShowDialog = true;
    private String mLunchStrType = "";
    private ISendCallback sunmiBack = new ISendCallback() {
        @Override
        public void onSendSuccess(long taskId) {
            myHandler.postDelayed(delayRun, Constant.TIME_SCREEN_JUMP);
        }

        @Override
        public void onSendFail(int errorId, String errorInfo) {
            Toast.makeText(context, errorInfo, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSendProcess(long totle, long sended) {
        }
    };
    private TextWatcher tWatcher = new TextWatcher() {
        //text  输入框中改变前的字符串信息 start 输入框中改变后的字符串的起始位置
        // count输入框中改变前的字符串的位置 默认为0 after 输入框中改变后的一共输入字符串的数量
        @Override
        public void beforeTextChanged(CharSequence text, int start,
                                      int icount, int iafter) {
        }

        @Override
        public void onTextChanged(CharSequence text, int start,
                                  int icount, int iafter) {
            if (start == Constant.CARD_LENGTH - 1) {
                String card = text.toString();
                if (!Constant.URGENT_TYPE) {
                    lunchPay(card);
                } else {
                    addSqlit(card, String.valueOf(System.currentTimeMillis()), 1);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_lunch_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = AccountApplication.getInstance();

        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            reloadInfo();
//            et_lunchId.setText("");
//            setCardnull();
//            if(!Constant.URGENT_TYPE){
//                tv_lunchNum.setText("人次：" + amount);
//                adapter=new LunchAdapter(getActivity(),lunchList);
//                list_lunch.setAdapter(adapter);
//            }else{
//                //紧急情况下
//                getlunchNum();
//            }
//            if(binings!=null && diningAdapter!=null){
//                    countDialogTime();
//            }
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        reloadInfo();
    }

    /**
     * 在fragment切换和休眠的时候重新加载
     */
    private void reloadInfo() {
        et_lunchId.setText("");
        setCardnull();
        if (!Constant.URGENT_TYPE) {
            tv_lunchNum.setText("人次：" + amount);
            adapter = new LunchAdapter(getActivity(), lunchList);
            list_lunch.setAdapter(adapter);
        } else {
            //紧急情况下
            getlunchNum();
        }
        if (binings != null && diningAdapter != null) {
            countDialogTime();
        }
    }

    /**
     * 计算弹出dialog的时间
     */
    private void countDialogTime() {
        int timeArea = (int) ((System.currentTimeMillis() - firstTime) / (1000 * 60 * 60));
        setDiningType();
        if (timeArea >= 2) {
            dialogSelect();
        }
    }

    /**
     * 获取默认的刷卡类型
     */
    private void setDiningType() {
        int type = SysTimeManage.getInstage().getOrderType(System.currentTimeMillis());
        for (int i = 0; i < binings.size(); i++) {
            if (binings.get(i).getId() == type) {
                mIndex = i;
                mType = type;
                continue;
            }
        }
        diningAdapter.selectItem(mIndex);
        diningAdapter.notifyDataSetChanged();
        tv_lunchType.setText(LunchTypeUtil.lunchType(mType));
    }

    private void initView() {
        et_lunchId = (EditText) mView.findViewById(R.id.et_lunchId);
        tv_lunchNum = (TextView) mView.findViewById(R.id.tv_lunchNum);
        list_lunch = (ListView) mView.findViewById(R.id.list_lunch);
        grid_diningType = (GridView) mView.findViewById(R.id.grid_diningType);
        rl_select = (RelativeLayout) mView.findViewById(R.id.rl_select);
        btn_clearCard = (Button) mView.findViewById(R.id.btn_clearCard);
        tv_lunchType = (TextView) mView.findViewById(R.id.tv_lunchType);

        et_lunchId.requestFocus();
        et_lunchId.addTextChangedListener(tWatcher);
        btn_clearCard.setOnClickListener(this);
        showDiningType();
        tv_lunchType.setText(LunchTypeUtil.lunchType(mType));

        lunchList = new ArrayList<>();

        if (!Constant.URGENT_TYPE) {
            tv_lunchNum.setText("人次：" + amount);
            adapter = new LunchAdapter(getActivity(), lunchList);
            list_lunch.setAdapter(adapter);

        } else {
            //紧急情况下
            getlunchNum();
        }

    }

    private void showDiningType() {
        String roles = SPManage.getInstance().getString("roles");
        if (TextUtils.isEmpty(roles)) {
            return;
        }
        Gson gson = new Gson();
        binings = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(roles);
            for (int i = 0; i < array.length(); i++) {
                RoleBean bean = gson.fromJson(array.get(i).toString(), RoleBean.class);
                //显示固定的几种
                if (bean.getId() == 0 || bean.getId() == 1 || bean.getId() == 2
                        || bean.getId() == 3 || bean.getId() == 6 || bean.getId() == 12
                        || bean.getId() == 13) {
                    binings.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (binings.size() == 0) {
            rl_select.setVisibility(View.GONE);
            return;
        }

        mType = binings.get(0).getId();
        if (binings.size() <= 1) {
            rl_select.setVisibility(View.GONE);
            return;
        }

        grid_diningType.setFocusable(false);
        grid_diningType.setNumColumns(binings.size());
        diningAdapter = new DiningTypeAdapter(context, binings);
        grid_diningType.setAdapter(diningAdapter);
        setDiningType();
        dialogSelect();
        grid_diningType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mIndex = i;
                mType = binings.get(i).getId();
                tv_lunchType.setText(LunchTypeUtil.lunchType(mType));
                diningAdapter.selectItem(i);
                diningAdapter.notifyDataSetChanged();

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_clearCard:
                et_lunchId.setText("");
                et_lunchId.requestFocus();
                break;
            default:
                break;
        }
    }

    /**
     * dialog选择就餐类型
     */
    private void dialogSelect() {
        firstTime = System.currentTimeMillis();
        CustomDialog dialog = new CustomDialog(1, getContext(), "请选择就餐类型", binings,
                mIndex, new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
                mIndex = btn;
                mType = binings.get(btn).getId();
                tv_lunchType.setText(LunchTypeUtil.lunchType(mType));
//                        mLunchStrType=binings.get(btn).getName()+"人次:";
                diningAdapter.selectItem(btn);
                diningAdapter.notifyDataSetChanged();
            }
        });
        dialog.show();
    }

    /**
     * 计算午餐人数
     */
    private void getlunchNum() {
        long sysTime = System.currentTimeMillis();
        String date = SysTimeManage.getInstage().getDate(sysTime);
//        amount = where("date = ? and type=?", date,"1").count(U_SettletmentBean.class);
        int allAmount = where("date = ? and type=? ", date, "" + mType).count(U_SettletmentBean.class);
        tv_lunchNum.setText("人次：" + allAmount);
        selist = new ArrayList<>();
        uWAdapter = new U_LunchAdapter(getContext(), selist);
        list_lunch.setAdapter(uWAdapter);
    }

    /**
     * 紧急模式下将数据加人数据库
     */
    private void addSqlit(String card, String nonce_str, int type) {
        synchronized (card) {
            et_lunchId.setText("");
//            int cardnub= DataSupport.where("no = ?",card).count(Card.class);
            ArrayList<Card> cardList = (ArrayList<Card>)
                    DataSupport.where("no = ?", card).find(Card.class);
            if (cardList == null || cardList.size() < 1) {
                SoundPoolManage.getInstance().soundpPlay(2);
                et_lunchId.setText("");
                showScreen("", "刷卡过快");
//                Toast.makeText(context,"刷卡频率过快或付款码无效",Toast.LENGTH_SHORT).show();
                toastUtil.Short("刷卡过快")
                        .setToastBackground(Color.WHITE, 0).show();
                return;
            }
            long sysTime = System.currentTimeMillis();
            String date = SysTimeManage.getInstage().getDate(sysTime);

//            int num= DataSupport.where("card = ? and type = ? and date=?" ,card,"1",date )
//                    .count(U_SettletmentBean.class);
            int num = 0;
            if (num <= 2) {
                String id = SysTimeManage.getInstage().getOrderId(sysTime);
//                int type=SysTimeManage.getInstage().getOrderType(sysTime);
                String time = SysTimeManage.getInstage().getDateTime(sysTime);
                U_SettletmentBean settl = new U_SettletmentBean(id, card,
                        mType, "0", time, 0, num + 1, 0, date, 0, nonce_str, 0, "");
                boolean save = settl.save();

                if (save) {
                    SoundPoolManage.getInstance().soundpPlay(1);
//                    amount = amount + 1;
                    tv_lunchNum.setText("人次：" + amount);
//                    Toast.makeText(context,"支付成功",Toast.LENGTH_SHORT).show();
                    toastUtil.Short("支付成功").setToastBackground(Color.WHITE, 0).show();
                    showScreen("", "支付成功");
                    if (type == 0) {
                        int cardNum = 1;
                        for (LunchBean l : lunchList) {
                            if (card.equals(l.getNo())) {
                                cardNum = l.getNum() + 1;
                                break;
                            }
                        }
                        lunchList.add(0, new LunchBean(cardList.get(0).getName(),
                                cardNum, "扣款成功", "0", mType, 0, card));
                        adapter.notifyDataSetChanged();
                        return;
                    }
                    int allAmount = where("date = ? and type=? ", date, "" + mType).count(U_SettletmentBean.class);
                    tv_lunchNum.setText(String.format("人次：%s", allAmount));
                    selist.add(0, settl);
                    uWAdapter.notifyDataSetChanged();
                } else {
                    SoundPoolManage.getInstance().soundpPlay(2);
                    showScreen("", "支付失败");
//                    Toast.makeText(context,"刷卡失败",Toast.LENGTH_SHORT).show();
                    toastUtil.Short("刷卡失败")
                            .setToastBackground(Color.WHITE, 0).show();
                }
            } else {
                showScreen("", "超过次数");
                toastUtil.Short("超过次数")
                        .setToastBackground(Color.WHITE, 0).show();
//                Toast.makeText(context,"您已支付满三次",Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void lunchPay(final String id) {
        synchronized (id) {
            et_lunchId.setText("");
//            if(firstTime){
//                int timeArea= (int)((System.currentTimeMillis()-firstTime)/(1000*60*60));
//                setDiningType();
//                if(timeArea>=2){
//                    dialogSelect();
//                }
//            }
            if (id.equals(on_card) &&
                    System.currentTimeMillis() - nonce_str < 750) {
//                Toast.makeText(mContext,"刷卡频率过快",Toast.LENGTH_SHORT).show();
                toastUtil.Short("刷卡频率过快")
                        .setToastBackground(Color.WHITE, 0).show();
                return;
            }
            on_card = id;
            nonce_str = System.currentTimeMillis();

            Call<String> call = HttpManage.getReqLunchApi().
                    lunchPay(SPManage.getInstance().getToken(), id, mType + "", "" + nonce_str,
                            Constant.ACCESS_PAY_TYPE);
            call.enqueue(new StrCallback<String>() {
                @Override
                public void onSuccess(Response<String> response, String base) {
                    SoundPoolManage.getInstance().soundpPlay(1);
                    LunchBean lunch = gson.fromJson(base,
                            LunchBean.class);
//                        amount+=1;
                    lunchList.add(0, lunch);
                    if (lunchList.size() > 31) {
                        lunchList.remove(31);
                    }
                    if (lunch.getType() == 0) {
                        showScreen("姓名:"+lunch.getName(),"支付金额:"+lunch.getTotal()+
                                "\n余额:"+lunch.getBalance());
                    } else {
                        showScreen("支付成功", String.format("剩余%s次", lunch.getLeft()));
                    }

                    adapter.notifyDataSetChanged();
                    tv_lunchNum.setText(String.format(Locale.getDefault(),
                            "人次:%d", lunch.getAllnum()));
//                        setCardnull();
                }

                @Override
                public void onError(int code, String error) {

                    et_lunchId.setText("");
                    //超时默认成功
                    if (code == Constant.ERROR_TIMEOUT_CODE) {
                        addSqlit(id, String.valueOf(nonce_str), 0);
                    } else {
                        SoundPoolManage.getInstance().soundpPlay(2);
//                    Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
                        toastUtil.Short(error)
                                .setToastBackground(Color.WHITE, 0).show();
                        if (code == 200) {
                            showScreen("", "\t" + error);
//                        showScreen("\t"+error,"");
                        } else {
                            showScreen("", "支付失败");
                        }
                    }
                }
            });
        }
    }

    private void showScreen(String title, String content) {
        Toast.makeText(context,
                "title:" + title +"\n" + "content:" + content, Toast.LENGTH_SHORT).show();
        SunmiSdkManage.getInstance().showPrice(title,
                content, sunmiBack);
    }

    private void setCardnull() {
        nonce_str = 0x0;
        on_card = "";
    }
}
